import React, { Component } from "react";
import { messages } from "share/common";
import { connect } from 'react-redux'
import { Modal, Button, Form, Input, Select, Popover, message, Radio, Popconfirm } from 'antd'
import ResizeTable from "components/resize-table";
import credentialService from "./credential-definition-service";
import Selector from "components/selector";
const FormItem = Form.Item;
const { Option } = Select;

@Form.create()
@connect(mapStateToProps)
class ViewEntry extends Component {

  componentWillReceiveProps(nextProps) {
    if (nextProps.visible === true && nextProps.visible !== this.props.visible) {
      this.props.form.resetFields();
      this.getColumns(nextProps.setOfBooksId);
    }
  }

  state = {
    infoVisible: false,
    saveLoading: false,
    infoColumns: [],
    infoData: []
  };

  getColumns = setOfBooksId => {
    credentialService.getAllList(setOfBooksId).then(res => {
      let columns = [];
      if (res.data.length) {
        res.data.map(item => {
          columns.push({
            title: item.ledgerName,
            dataIndex: item.interfaceCode,
            width: 120,
            render: value => <Popover content={value}>{value}</Popover>
          })
        })
      }
      this.setState({ infoColumns: columns })
    })
  };

  handleOk = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { user, expandRecord, setOfBooksId, cancel } = this.props;
        let params = {
          businessCode: values.businessCode,
          entityType: Number(values.type),
          operatorOid: user.userOID,
          journalType: expandRecord.templateCode,
          transactionDetailIds: values.transactionDetailIds ? [values.transactionDetailIds] : [],
          forceRefresh: true,
          setOfBooksId,
          isPreview: values.isPreview,
          isCoverForced: values.isCoverForced
        };
        this.setState({ saveLoading: true });
        credentialService.buildEntry(params).then(res => {
          this.setState({ saveLoading: false }, () => {
            cancel();
            this.setState({
              infoData: res.data.map((item, index) => Object.assign(item, { index })),
              infoVisible: true
            });
          });
        }).catch(e => {
          const { viewError } = this.props;
          if (viewError) {
            Modal.confirm({
              title: messages('finance-2.key74')/*预览分录*/,
              content: e.response.data.message,
              onOk: () => this.handleView(e.response),
              onCancel: () => this.setState({ saveLoading: false })
            })
          } else {
            this.setState({ saveLoading: false });
            message.error(e.response.data.message);
          }
        })
      }
    })
  };

  handleView = data => {
    const { cancel } = this.props;
    credentialService.viewError(data.headers.spanid).then(res => {
      cancel();
      this.setState({
        infoData: JSON.parse(res.data.errorDetail).map((item, index) => Object.assign(item, { index })),
        infoVisible: true,
        saveLoading: false
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ saveLoading: false });
    });
  };

  render() {
    const { visible, expandRecord, cancel, tenant } = this.props;
    const { infoVisible, saveLoading, infoData, infoColumns } = this.state;
    const { getFieldsValue, getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };
    const result = getFieldsValue();
    return (
      <div>
        <Modal
          visible={visible}
          footer={(
            <div>
              <Button onClick={cancel}>{messages('common.cancel')/*取消*/}</Button>
              {
                result.isPreview ? (
                  <Button
                    onClick={this.handleOk}
                    type='primary'
                    loading={saveLoading}
                  >{messages('common.ok')/*确定*/}</Button>
                ) : (
                  <Popconfirm title={<div>
                    <div>提示</div>
                    <div style={{marginTop: '8px'}}>重新生成凭证模式下，将会删除已生成凭证，然后重新生成，可能存在与下游系统的对接问题，如凭证重复等，请确认是否重新生成！</div>
                  </div>} onConfirm={() => this.handleOk()}>
                    <Button
                      type='primary'
                      loading={saveLoading}
                    >{messages('common.ok')/*确定*/}</Button>
                  </Popconfirm>
                )
              }
            </div>
          )}
          onCancel={cancel}
          title={messages('finance-2.key83')/*分录生成*/}
        >
          <Form>
            <FormItem label={messages('common.document.code')/*单号*/} {...formItemLayout}>
              {getFieldDecorator('businessCode', {
                rules: [{ required: true, message: messages('common.please.input')/*请输入*/ }],
              })(
                <Input placeholder={messages('common.please.input')/*请输入*/} autoComplete='off'/>
              )}
            </FormItem>
            <FormItem label={messages('finance-2.key84')/*单号类型*/} {...formItemLayout}>
              {getFieldDecorator('type', {
                rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
                initialValue: expandRecord.templateName ?
                  (~expandRecord.templateName.indexOf('还款') ? '1008' :
                    ~expandRecord.templateName.indexOf('借款') ? '3001' : '1002') : '1002'
              })(
                <Select placeholder={messages('common.select')/*请选择*/}>
                  <Option key={'1002'}>报销单</Option>
                  <Option key={'3001'}>借款单</Option>
                  <Option key={'1008'}>还款单</Option>
                  <Option key={'7001'}>付款申请单</Option>
                </Select>
              )}
            </FormItem>
            {
              result.type && result.businessCode && expandRecord.templateCode !== 'GL_AMORTIZATION' && (
                <FormItem label={'流水号'} {...formItemLayout}>
                  {getFieldDecorator('transactionDetailIds')(
                    <Selector
                      type='entry-information'
                      params={{
                        businessCode: result.businessCode,
                        tenantId: tenant.id,
                        journalTemplateId: expandRecord.id,
                        type: Number(result.type)
                      }}
                    />
                  )}
                </FormItem>
              )
            }
            {
              result.type && result.businessCode && expandRecord.templateCode === 'GL_AMORTIZATION' && (
                <FormItem label={'摊销号'} {...formItemLayout}>
                  {getFieldDecorator('transactionDetailIds')(
                    <Input/>
                  )}
                </FormItem>
              )
            }
            <FormItem label={'模式'} {...formItemLayout}>
              {getFieldDecorator('isPreview', {
                rules: [{ required: true }],
                initialValue: true
              })(
                <Radio.Group options={[
                  { label: '预览', value: true },
                  { label: '重新生成', value: false }
                ]}/>
              )}
            </FormItem>
            {
              !result.isPreview && (
                <FormItem label={'生成方式'} {...formItemLayout}>
                  {getFieldDecorator('isCoverForced', {
                    rules: [{ required: true }],
                    initialValue: false
                  })(
                    <Radio.Group options={[
                      { label: '补偿', value: false },
                      { label: '覆盖', value: true }
                    ]}/>
                  )}
                </FormItem>
              )
            }
          </Form>
        </Modal>
        <Modal
          visible={infoVisible}
          footer={null}
          width={900}
          title={messages('finance-2.key85')/*预览信息*/}
          onCancel={() => this.setState({ infoVisible: false })}
        >
          <ResizeTable
            dataSource={infoData}
            rowKey={'index'}
            bordered
            pagination={false}
            scroll={{ x: true }}
            columns={infoColumns}
          />
        </Modal>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    user: state.login.user
  }
}

export default ViewEntry
